#include "widget.h"
#include "ui_widget.h"


#define TAB_IMAGE	0
#define TAB_RESULT	1
#define TAB_ABOUT	3


//--------------------------------
Widget::Widget (QWidget *parent) :
	QWidget (parent),
	ui (new Ui::Widget)
{
	ui->setupUi (this);

	ui->version->setAlignment (Qt::AlignCenter);
	ui->version->setText (QString ("%1 - version %2")
						  .arg (Config::appName ())
						  .arg (Config::appVersion ()));

	m_tesseract = new Tesseract (this);
	m_config = new Config (this);
	m_spellChecker = new SpellChecker (this);
	m_fileDialog = new FileDialog (this);
	m_fileDialog->setDirectory (QDesktopServices::storageLocation (QDesktopServices::PicturesLocation));


	connect (ui->buttonOpen,
			 SIGNAL(clicked()),
			 this,
			 SLOT(onButtonOpenClicked()));

	connect (ui->contrast,
			 SIGNAL(valueChanged(int)),
			 this,
			 SLOT(onContrastModified(int)));

	connect (ui->scale1,
			 SIGNAL(valueChanged(double)),
			 this,
			 SLOT(onScale1Modified(double)));

	connect (ui->scale2,
			 SIGNAL(valueChanged(double)),
			 this,
			 SLOT(onScale2Modified(double)));

	connect (ui->runOCR,
			 SIGNAL(clicked()),
			 this,
			 SLOT(onRunOCRClicked()));

	connect(m_tesseract,
			SIGNAL(endOfOCR(QString)),
			this,
			SLOT(onEndOfOCR(QString)));

	connect(ui->spelling,
			SIGNAL(clicked()),
			this,
			SLOT(onSpellingClicked()));

	connect(ui->copyToClipboard,
			SIGNAL(clicked()),
			this,
			SLOT(onCopyToClipBoardClicked()));

	connect (ui->saveAs,
			 SIGNAL(clicked()),
			 this,
			 SLOT(onSaveAsClicked()));

	setWindowTitle (QString ("%1 - version %2")
					.arg (Config::appName ())
					.arg (Config::appVersion ()));

	setWindowIcon (Config::appIcon ());

	clear ();
}
//----------------
Widget::~Widget()
{
	delete ui;
}
//-------------------
void Widget::clear ()
{
	ui->image1->setPixmap (QPixmap ());
	ui->image1->setText (QString ());
	ui->image1->setToolTip (QString ());
	ui->image2->setPixmap (QPixmap ());
	ui->image2->setText (QString ());
	ui->image2->setToolTip (QString ());
	m_image1 = QImage ();
	m_image2 = QImage ();
	ui->imageName->setText (tr ("Aucune image chargée"));
	ui->tabs->setCurrentIndex (TAB_IMAGE);
	ui->contrast->setValue (50);

	ui->runOCR->setDisabled (true);
	ui->contrast->setDisabled (true);
	ui->scale1->setValue (1.0);
	ui->scale2->setValue (1.0);
	ui->scale1->setDisabled (true);
	ui->scale2->setDisabled (true);

	setImageModified (true);
	setMode (0);
}
//---------------------------------------------
void Widget::onScale1Modified (double size)
{
	ui->image1->setPixmap(QPixmap::fromImage(m_image1.scaledToHeight (m_image1.height () * size,
																	  Qt::SmoothTransformation)));
}
//------------------------------------
void Widget::onScale2Modified (double /*size*/)
{
	onContrastModified (ui->contrast->value ());
}
//-------------------------------------------
void Widget::onContrastModified(int contrast)
{
	setImageModified (true);
	contrast = contrast * 255 / 100;
	m_image2 = m_image1.convertToFormat (QImage::Format_RGB32);
	m_image2 = m_image2.scaledToHeight (m_image1.height () * ui->scale2->value (), Qt::SmoothTransformation);

	QRgb black = qRgb (0, 0, 0);
	QRgb white = qRgb (255, 255, 255);
	int width = m_image2.width ();
	int height = m_image2.height ();
	int indexV;
	int indexW;
	QRgb* rgb;

	for (indexV = 0 ; indexV < height; indexV++)
	{
		rgb = (QRgb*) m_image2.scanLine (indexV);
		for (indexW = 0 ; indexW < width ; indexW++)
		{
			if (qGray (*rgb) < contrast)
				*rgb = black;
			else
				*rgb = white;
			rgb++;
		}
	}

	m_image2 = m_image2.convertToFormat (QImage::Format_Mono/*, Qt::MonoOnly | Qt::ThresholdDither*/);

	ui->image2->setPixmap(QPixmap::fromImage (m_image2));
}
//---------------------------------
void Widget::onButtonOpenClicked ()
{
	QString imageName = m_fileDialog->getOpenFileName (this,
													 tr ("Charger une image"),
													 QDesktopServices::storageLocation (QDesktopServices::PicturesLocation),
													 loadFilters ());

	if (imageName.isEmpty ()) return;

	open (imageName);

}
//-----------------------------------
void Widget::open (QString imageName)
{
	clear ();

	if (! m_image1.load (imageName))
	{
		qDebug () << tr ("Erreur de chargement de l'image %1").arg (imageName);
		return;
	}

	QStringList propertyList;

	propertyList << tr ("Largeur : %1, hauteur %2").arg (m_image1.width ()).arg (m_image1.height ());
	propertyList << tr ("%1 bpp").arg (m_image1.depth ());
	int colorCount = m_image1.colorCount ();
	if (colorCount)
		propertyList << tr ("%1 couleurs").arg (colorCount);

	foreach (QString prop, m_image1.textKeys ())
	{
		if (! prop.isEmpty ())
			propertyList << tr ("%1=%2").arg (prop).arg (m_image1.text (prop));
	}

	ui->image1->setToolTip (propertyList.join ("\n"));

	ui->image1->setPixmap(QPixmap::fromImage(m_image1));

	QFileInfo fi (imageName);
	ui->imageName->setText (fi.baseName () + '.' + fi.completeSuffix ());
	onScale2Modified (ui->scale2->value ());
	ui->runOCR->setEnabled (true);
	ui->contrast->setEnabled (true);
	ui->scale1->setEnabled (true);
	ui->scale2->setEnabled (true);
	setImageModified (true);
}
//-----------------------------
void Widget::onRunOCRClicked ()
{
	if (m_mode == 0)
	{
		if (imageModified ())
		{
			QString fileName (Config::appWorkPath () + "tmp" + QDateTime::currentDateTime ().toString ("yyyy-MM-dd-hh-mm-ss-zzz") + ".tif");

			if (! m_image2.save (fileName, "TIFF", 0))
			{
				qDebug () << tr ("L'enregistrement au format TIF a échoué");
				return;
			}
			setImageModified (false);
			m_tesseract->run (fileName);
		}
		else
		{
			setMode (1);
		}
	}
	else
	{
		setMode (0);
	}
}
//----------------------------------------------
void Widget::onEndOfOCR(QString resultFileName)
{


	QFile file (resultFileName);

	if (!file.open (QIODevice::ReadOnly | QIODevice::Text))
	{
		qDebug () << tr ("Impossible d'ouvrir le fichier %1").arg (resultFileName);
		return;
	}

	QTextStream in (&file);
	in.setCodec ("UTF-8");

	m_text = in.readAll ();


	QTextEdit* text = ui->OCRResult;
	text->clear ();
	text->setTextColor (Qt::black);
	text->setFontUnderline (false);

	text->setPlainText (m_text);

	setMode (1);	// on passe en mode visualisation texte + correction

	text->moveCursor (QTextCursor::Start);
}
//------------------------------
void Widget::onSpellingClicked()
{
	m_spellChecker->run (m_text);
}
//-----------------------------
void Widget::setMode(int mode)
{
	if (mode == 0)
	{
		ui->runOCR->setText (tr ("Analyser cette image >>"));
	}
	else
	{
		ui->runOCR->setText (tr ("<< Retour aux modifications"));
	}

	ui->stacked->setCurrentIndex (mode);
	m_mode = mode;
}
//--------------------------------------
void Widget::onCopyToClipBoardClicked()
{
	ui->OCRResult->selectAll ();
	ui->OCRResult->copy ();
	ui->OCRResult->moveCursor (QTextCursor::Start);
}
//------------------------------
void Widget::onSaveAsClicked ()
{
//	m_fileDialog->getSaveFileName (this,
//								   tr ("Enregistrer le texte sous le nom..."),
//								   QDesktopServices::storageLocation (QDesktopServices::DocumentsLocation),
//								   tr ("Fichiers texte (*.txt)"),
//								   0,
//								   QString ("txt"));

}
